<?php
class Zixun_model extends CI_Model{
	function __construct(){
		parent::__construct();
	}

	public function action($pid){
		
		$data['pid'] = $pid;
		$data['uid'] = $this->auth->uid ? $this->auth->uid : 0;
		$data['uname'] = $this->auth->uname ? $this->auth->uname : '匿名网友';
		$data['content'] = $this->form_validation->set_value('content');
		$data['point_type'] = 1;
		$data['time'] = date('Y-m-d H:i:s');
		if($this->db->insert('zixun',$data)){
			return array('status'=>true);
		}else{
			return array('status'=>false,'msg'=>'评论失败，可能网络出错！');
		}
	}


	public function get_zixun($pid,$point_type,$start=0,$limit=null){
		
		$this->db->where('pid',$pid);
		$this->db->where('point_type',$point_type);
		$this->db->order_by('time','DESC');
		$this->db->limit($limit,$start);

		$query = $this->db->get('zixun');
		if($query->num_rows){
			$zixun = $query->result_id();

			foreach($zixun as $z){
				$cid[] = $z->id;
			}
			$this->db->where_in('cid',$cid);
			$this->db->select('cid,content,uname,uid,time');
			$zr =$this->db->get('zixun_reply')->result_id();
			foreach($zixun as $z){
				if(isset($zr[$z->id])){
					$z->reply = $zr[$z->id];
				}
			}
			return $zixun;
		} else {return false;}
	}

	public function get_zixun_num($pid,$point_type){
		$this->db->where('pid',$pid);
		$this->db->where('point_type',$point_type);
		return $this->db->count_all_results('zixun');
	}

	public function add_reply($cid,$content){
		$data['content'] = $content;
		$data['uid'] = $this->auth->uid;
		$data['uname'] = $this->auth->uname;

		$query = $this->db->get_where('zixun_reply',array('cid'=>$cid));
		if($query->num_rows()){
			$this->db->where('cid',$cid);
			if($this->db->update('zixun_reply',$data)){
				return array('status'=>true);
			}else{
				return array('status'=>false,'msg'=>'回复失败，可能网络出错！');
			}
		}else{
			$data['cid'] = $cid;
			$data['time'] = date('Y-m-d H:i:s');
			if($this->db->insert('zixun_reply',$data)){
				return array('status'=>true);
			}else{
				return array('status'=>false,'msg'=>'回复失败，可能网络出错！');
			}
		}
	}
}